﻿using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using K9Nano.IM.Areas.Chat.Dto;
using K9Nano.IM.Areas.Chat.ViewModels.AccountVMs;
using K9Nano.IM.Controllers;
using K9Nano.IM.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;

namespace K9Nano.IM.Areas.Chat.Controllers
{
    [Area("Chat")]
    public class AccountController : K9BaseController
    {
        [Public]
        [HttpGet]
        public async Task<IActionResult> Login(ChatLoginVM vm)
        {
            if (!ModelState.IsValid)
            {
                return View("Error");
            }

            vm.DoInit();

            if (vm.LoginUserInfo == null)
            {
                return View("Error");
            }

            // SignIn
            var properties = new AuthenticationProperties();
            var principal = vm.LoginUserInfo.CreatePrincipal();
            principal.AddIdentity(new ClaimsIdentity(new[]
            {
                new Claim("chat_app", vm.ChatApp.ID.ToString()),
                // todo session
            }));
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, properties);

            return Redirect("/im/chat/customer");
        }

        [AllRights]
        [HttpGet]
        public async Task<IActionResult> Staff()
        {
            var staff = await DC.Set<FrameworkUserRole>()
                .Include(x => x.Role)
                .AnyAsync(x => x.UserId == this.LoginUserInfo.Id && x.Role.RoleCode == "100",
                    HttpContext.RequestAborted);
            if (!staff)
            {
                return Redirect("/Login/Login?Redirect=/Chat/Account/Staff");
            }

            var app = await DC.Set<User>()
                .Where(x => x.ID == this.LoginUserInfo.Id)
                .Select(x => x.AppId)
                .FirstOrDefaultAsync(HttpContext.RequestAborted);

            var properties = new AuthenticationProperties();
            var principal = LoginUserInfo.CreatePrincipal();
            principal.AddIdentity(new ClaimsIdentity(new[]
            {
                new Claim("chat_app", app.ToString()),
                new Claim("role", "staff"),
            }));
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, properties);

            return Redirect("/im/chat/staff");
        }

        [Public]
        [HttpGet]
        public IActionResult Demo()
        {
            var vm = CreateVM<DemoVM>();
            return View(vm);
        }

        [Public]
        [HttpPost]
        public IActionResult Demo(DemoVM vm)
        {
            vm.DoInit();
            vm.Area = "Chat";
            return RedirectToAction(nameof(Login), "Account", vm);
        }

        [Public]
        [HttpGet]
        public AppCustomer DemoCustomer(string id)
        {
            return new AppCustomer
            {
                Id = id,
                Nickname = $"Test({id})",
                Name = "测试",
                Avatar = "http://tva1.sinaimg.cn/crop.0.0.180.180.180/7fde8b93jw1e8qgp5bmzyj2050050aa8.jpg"
            };
        }
    }
}